/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package researchgrants.parts.GrantRequest.perennialStipends;

import java.awt.Color;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.ChangeEvent;
import researchgrants.parts.panels.*;
import java.awt.Component;
import java.awt.FlowLayout;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import researchgrants.parts.LoggedData.panels.LoggedDataPanelsCurrency;
import javax.swing.event.ChangeListener;
import researchgrants.parts.db.Db;
import researchgrants.parts.panelsManager.LoggedDataPanelsManager;
import researchgrants.utils.MyDialog;

/**
 * A panel for a signle year within PanelsPerennialStipends
 * Displays and allows editing of DirectMoney and IndirectMoney
 * @author DOStudent1
 */
public class PanelsStipend extends PanelsCompoundView implements ChangeListener {

    // Support a default value, when no logged data is provided
    private boolean hasDefaultValue=false;
    private Long defaultDirectMoney;
    private Long defaultIndirectMoney;
    // Those default values must be initialized to be able to save the content
    private Integer defaultYear;
    private Integer defaultPerennialStipendsID;

    // if an existing Stipend is being referenced
    private Stipend stipend=null;
    private boolean isDataInitialized=false;
     
    // global-style components
    LoggedDataPanelsManager directMoneyView;
    LoggedDataPanelsCurrency directMoneyPanel;
    LoggedDataPanelsManager indirectMoneyView;
    LoggedDataPanelsCurrency indirectMoneyPanel;
    
    
    // New Stipend, sets the default values
    public void setDefaultValue(Integer defaultYear, Long defaultDirectMoney, Long defaultIndirectMoney) {
        this.defaultYear=defaultYear;
        this.defaultDirectMoney=defaultDirectMoney;
        this.defaultIndirectMoney=defaultIndirectMoney;
        hasDefaultValue=true;
    }
    
    // New Stipend, sets the default id, just before saving (not available before saving)
    void setDefaultPerennialStipendsId(int newPerennialStipendsId) {
        defaultPerennialStipendsID=newPerennialStipendsId;
    }
    
    // Sets an existing stipend
    public void setData(Stipend stipend) {
        this.stipend=stipend;
        isDataInitialized=true;
    }

    
    // Gets the component
    @Override
    public Component getComponent() {
        JPanel pnlContent=new JPanel();
        pnlContent.setBorder(new LineBorder(Color.BLACK));
        pnlContent.setLayout(new FlowLayout(FlowLayout.LEFT, 8, 0));
        
        // Displays the yearly index
        JLabel titleLabel;
        if (isDataInitialized) {
            titleLabel=new JLabel("Year " + stipend.getYearIndex() + ":");
        } else {
            titleLabel=new JLabel("Year " + defaultYear + ":");
        }
        titleLabel.setAlignmentX(0);
        pnlContent.add(titleLabel);
        
        ///////////////////////////
        // adds the direct money
        ///////////////////////////
        
        JPanel pnlDirectMoney=new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        pnlDirectMoney.setAlignmentX(0);
        pnlDirectMoney.add(new JLabel("Direct Money:"));
        // adds a currency panel for the direct money
        directMoneyPanel=new LoggedDataPanelsCurrency();
        if (isDataInitialized) {
            directMoneyPanel.setData(stipend.getLoggedDataDirectMoney());
        } else {
            if (hasDefaultValue) {
                if (defaultDirectMoney!=null) {
                    directMoneyPanel.setDefaultValue(Long.toString(defaultDirectMoney));
                }
            // if new, then the needs to signal for changes for validation
            directMoneyPanel.addChangeListener(this);
            }
        }
        directMoneyPanel.setParent(getParentWindow(), getParentContainer());
        // add a manager for the direct money - to facilitate saving
        directMoneyView=new LoggedDataPanelsManager();
        directMoneyView.startAsNew(!isDataInitialized);
        directMoneyView.setMandatory(false);
        directMoneyView.setPanels(directMoneyPanel);
        directMoneyPanel.addChangeListener(directMoneyView);
        pnlDirectMoney.add(directMoneyView);
        directMoneyView.display();
        pnlContent.add(pnlDirectMoney);

        /////////////////////////////
        // adds the indirect money
        /////////////////////////////
        
        JPanel pnlIndirectMoney=new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        pnlIndirectMoney.setAlignmentX(0);
        pnlIndirectMoney.add(new JLabel("Indirect Money:"));
        // adds a currency panel for the direct money
        indirectMoneyPanel=new LoggedDataPanelsCurrency();
        if (isDataInitialized) {
            indirectMoneyPanel.setData(stipend.getLoggedDataIndirectMoney());
        } else {
            if (hasDefaultValue) {
                if (defaultIndirectMoney!=null) {
                    indirectMoneyPanel.setDefaultValue(Long.toString(defaultIndirectMoney));
                }
            }
            // if new, then the needs to signal for changes for validation
            indirectMoneyPanel.addChangeListener(this);
        }
        indirectMoneyPanel.setParent(getParentWindow(), getParentContainer());
        // add a manager for the direct money - to facilitate saving
        indirectMoneyView=new LoggedDataPanelsManager();
        indirectMoneyView.startAsNew(!isDataInitialized);
        indirectMoneyView.setMandatory(false);
        indirectMoneyView.setPanels(indirectMoneyPanel);
        indirectMoneyPanel.addChangeListener(indirectMoneyView);
        pnlIndirectMoney.add(indirectMoneyView);
        indirectMoneyView.display();
        pnlContent.add(pnlIndirectMoney);
        
        return(pnlContent);
    }

    // Fires when the years had changed.
    // Should change the view of the years.
    @Override
    public void stateChanged(ChangeEvent e) {
        notifyAllChangeListeners(new ChangeEvent(this));
    }

    // the year's panel is valid if both fields' panels are valid
    @Override
    public boolean isValid() {
        return(directMoneyPanel.isValid() && indirectMoneyPanel.isValid());
    }

    /**
     * saves this particular year into the database
     */
    public void saveData() {
        try {
            Connection conn = Db.openDbConnection();
            PreparedStatement createGrantRequestStatement = Db.createPreparedStatement(conn, "INSERT INTO tblStipends (PerennialStipendsID, YearIndex, DirectMoneyRef, IndirectMoneyRef, Active) VALUES (?, ?, ?, ?, 1)");


            ////////////////////////////////////
            // Save all different data pieces
            ////////////////////////////////////
            // saves using the given perennialStipendsId
            createGrantRequestStatement.setInt(1, defaultPerennialStipendsID);
            // saves using the given year index
            createGrantRequestStatement.setInt(2, defaultYear);
            // saves the entered values
            createGrantRequestStatement.setInt(3, MyDialog.saveLoggedDataPanelsManagerData(directMoneyView));
            createGrantRequestStatement.setInt(4, MyDialog.saveLoggedDataPanelsManagerData(indirectMoneyView));
            createGrantRequestStatement.executeUpdate();

            createGrantRequestStatement.close();
            Db.closeDbConnection(conn);
        } catch (SQLException ex) {
            Logger.getLogger(PanelsStipend.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
